﻿using System.Collections.Generic;

namespace QuailDb
{
    /// <summary>
    /// Simple thread-safe factory for objects
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class EasyFactory<T> where T : new()
    {
        private static readonly Stack<T> ListStuff = new Stack<T>();

        /// <summary>
        /// Returns a valid instance of T
        /// </summary>
        /// <returns>A T instance</returns>
        public T Get()
        {
            lock(ListStuff)
            {
                if (ListStuff.Count == 0)
                    return new T();

                return ListStuff.Pop();
            }
        }

        /// <summary>
        /// Puts a T object back into the list
        /// </summary>
        /// <param name="thing">The thing to put back into the list.</param>
        public void Replace(T thing)
        {
            lock(ListStuff)
                ListStuff.Push(thing);
        }

        /// <summary>
        /// Clears the factory of all objects
        /// </summary>
        public void Clear()
        {
            lock (ListStuff)
                ListStuff.Clear();
        }
    }
}
